<script setup>
import { ref, onMounted } from 'vue'
import * as echarts from 'echarts'
import anlyze from '../../apis/anlyze.js'
import taskCotgary from '../../utils/taskCotgray.js' // 导入你的分类映射

const chart = ref(null)

const fetchData = async () => {
  try {
    const res = await anlyze.getTaskCategory() // 假设接口返回 { data: [6, 5, 4, 4, 1, 2, 9, 2] }

    // 将统计数据和分类映射结合
    const chartData = res.map((count, index) => {
      const category = taskCotgary.find(item => item.value === String(index))
      return {
        name: category ? category.label : `未知分类(${index})`,
        value: count
      }
    })

    const option = {
      title: {
        text: '任务类型分布',
        left: 'center',
        textStyle: {
          fontSize: 18,
          fontWeight: 'bold'
        }
      },
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c} ({d}%)'
      },
      legend: {
        orient: 'vertical',
        right: 10,
        top: 'center',
        data: chartData.map(item => item.name)
      },
      series: [
        {
          name: '任务数量',
          type: 'pie',
          radius: ['40%', '70%'],
          center: ['40%', '50%'],
          avoidLabelOverlap: false,
          itemStyle: {
            borderRadius: 8,
            borderColor: '#fff',
            borderWidth: 2
          },
          label: {
            show: false,
            position: 'center'
          },
          emphasis: {
            label: {
              show: true,
              fontSize: 20,
              fontWeight: 'bold',
              formatter: '{b}\n{c} ({d}%)'
            }
          },
          labelLine: {
            show: false
          },
          data: chartData
        }
      ],
      color: [
        '#5470C6', '#91CC75', '#FAC858', '#EE6666',
        '#73C0DE', '#3BA272', '#FC8452', '#9A60B4',
        '#EA7CCC'
      ] // 自定义颜色，确保每个分类颜色不同
    }

    const myChart = echarts.init(chart.value)
    myChart.setOption(option)

    // 响应式调整
    window.addEventListener('resize', function() {
      myChart.resize()
    })
  } catch (error) {
    console.error('获取数据失败:', error)
  }
}

onMounted(fetchData)
</script>

<template>
  <div ref="chart" style="width: 100%; height: 500px;"></div>
</template>

<style scoped>
/* 可以添加一些响应式样式 */
@media (max-width: 768px) {
  div {
    height: 400px !important;
  }
}
</style>